import copy
import json
from typing import Dict

import requests

# from django.conf import settings
# from django.core.cache import cache
# from django.shortcuts import resolve_url
#
# from dash.models import Video
# from django_qq.models import SocialAuth

# 辅立码课 录入应用
app_id = 'cli_a5606572adf91013'
app_secret = 'go0d5uQ5nvL8FJ7AxcQitelmj5mYmqm0'
template_id = 'AAqCYFD5utO1S'
audit_video_msg_version = '1.0.0'

app_id = 'cli_a6371ce2cb6d1013'
app_secret = 'go0d5uQ5nvL8FJ7AxcQitelmj5mYmqm0'
template_id = 'AAqCYFD5utO1S'
audit_video_msg_version = '1.0.0'


#
# if settings.DEBUG:
# app_id = 'cli_a56065a3f26dd00d'
# app_secret = 'lRtqYJcArVJ614pshY4J7WdEJYk7aooL'
# template_id = 'AAqUMMmTFbQu7',
# audit_video_msg_version = '1.0.9'
#
# app_id = 'cli_a637dde6d6b91013'
# app_secret = 'yp2YJICAuSIzz9v08Fo7Ve0sFDon2PlB'
# template_id = 'AAqCY7zpOG9VE',
# audit_video_msg_version = '1.0.2'


# app_id = 'cli_a5606572adf91013'
# app_secret = 'lJAnYiekFaabogV8w7JX3exYmssmkGbz'
# template_id = 'AAq1lCe770JpF'
# audit_video_msg_version = '1.0.12'
#
# if settings.DEBUG:
#     app_id = 'cli_a56065a3f26dd00d'
#     app_secret = 'lRtqYJcArVJ614pshY4J7WdEJYk7aooL'
#     template_id = 'AAqUMMmTFbQu7',
#     audit_video_msg_version = '1.0.9'


class FeishuBridge(object):
    """
    发送飞书消息
    """

    def get_tenant_access_token(self):
        key = 'feishu_tenant_access_token'
        url = 'https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal'
        data = requests.post(url, data=dict(app_id=app_id, app_secret=app_secret))
        if data.status_code == 200:
            data_json = data.json()
            tenant_access_token = data_json.get('tenant_access_token')

            return tenant_access_token

    def get_union_id(self, user_phone_id: Dict[str, int]):
        tenant_access_token = self.get_tenant_access_token()
        url = 'https://open.feishu.cn/open-apis/contact/v3/users/batch_get_id?user_id_type=union_id'
        auth_header = dict(Authorization=f'Bearer {tenant_access_token}')
        data = requests.post(
            url=url,
            data=json.dumps(dict(mobiles=list(user_phone_id.keys()))),
            headers=auth_header
        )
        user_union_id = {}
        print(data.json())
        if user_list := data.json().get('data', {}).get('user_list'):
            for item in user_list:
                mobile = item['mobile']
                union_id = item.get('user_id')
                if not union_id:
                    continue

                user_id = user_phone_id[mobile]

                user_union_id[user_id] = union_id

        return user_union_id

    def send_audit_video_msg(self, video_id: int, user_id_phone: Dict[int, str]):

        user_id_union_id = self.get_union_id(user_id_phone)
        print('user_id_union_id')
        domain = 'http://192.168.5.233'
        video_url = domain + ''
        json_data_tpl = {
            'content': {
                'type': 'template',
                'data': {
                    'template_id': template_id,
                    'template_version_name': audit_video_msg_version,
                    'template_variable': {
                        "id": f"ID:123",
                        "filetype": "DOCX",
                        "filesize": "DOCX",
                        "gread_name": "DOCX",
                        "subject_title": "DOCX",
                        "tasknum": "DOCX",
                        "msg": "DOCX",

                    }
                }
            },  # ou_c7457c7632ae01e695e6e2692c8c5149
            'msg_type': 'interactive',
        }
        tenant_access_token = self.get_tenant_access_token()
        auth_header = dict(Authorization=f'Bearer {tenant_access_token}')
        url = 'https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=union_id'
        for user_id, union_id in user_id_union_id.items():
            json_data = copy.deepcopy(json_data_tpl)
            # json_data['content']['data']['template_variable'].update(
            #     approve=dict(user_id=user_id, video_id=video_id, action='approve'),
            #     reject=dict(user_id=user_id, video_id=video_id, action='reject')
            # )
            json_data.update(receive_id=union_id)
            json_data['content'] = json.dumps(json_data['content'])
            print(json.dumps(json_data, ensure_ascii=False))
            try:
                x = requests.post(
                    url=url,
                    data=json_data,
                    headers=auth_header
                )
                print(x.json())
            except:
                pass


feishu_client = FeishuBridge()
user_id_phone = {'15226500832': 15226500832, '15933983339': 15933983339, '15097473391': 15097473391}
user_id_phone = {'15933983339': 15933983339,}
x = feishu_client.send_audit_video_msg(1, user_id_phone)
# x = feishu_client.send_audit_video_msg(1, {'15933983339': 15933983339})

# user_id_union_id = feishu_client.get_union_id(user_id_phone)
print(x)
